/*
 * Region.cpp
 *
 *  Created on: 23.07.2011
 *      Author: seb
 */

#include "Region.h"
#include "../GameEngine.h"
#include "IMapGenerator.h"
#include "../entities/Player.h"

Region::Region(int regionX, int regionY) : x(regionX), y(regionY) {
	map = GameEngine::get().getMapGenerator()->generate(x * REGION_WIDTH, y * REGION_HEIGHT, REGION_WIDTH, REGION_HEIGHT);
}

Region::~Region() {
	// free map memory
	for (int x = 0; x < REGION_WIDTH; x++) {
		for (int y = 0; y < REGION_HEIGHT; y++) {
			delete map[x][y];
		}
		delete[] map[x];
	}

	delete[] map;
}

Entity*** Region::getMap() {
	return map;
}

int Region::getX() {
	return x;
}

int Region::getY() {
	return y;
}

bool Region::isWithinJoiningDistance(Player* player) {
	return (distanceToPoint(player->getX(), player->getY()) <= JOIN_DISTANCE);
}

bool Region::isWithinLeavingDistance(Player* player) {
	return (distanceToPoint(player->getX(), player->getY()) >= LEAVE_DISTANCE);
}

float Region::distanceToPoint(float px, float py) {
	// transform point into local space
	px -= x * REGION_WIDTH * MAP_TILE_SIZE;
	py -= y * REGION_HEIGHT * MAP_TILE_SIZE;
	// clamp
	float px2 = min(max(0.f, px), (float)REGION_WIDTH * MAP_TILE_SIZE);
	float py2 = min(max(0.f, py), (float)REGION_HEIGHT * MAP_TILE_SIZE);
	return sqrt(pow(px - px2, 2) + pow(py - py2, 2));
}

